//
//  RestaurantViewController.m
//  Park
//
//  Created by 123456 on 2017/12/4.
//  Copyright © 2017年 YTYangK. All rights reserved.
//

#import "RestaurantViewController.h"
#import "CategoryModel.h"
#import "TableViewHeaderView.h"
#import "LeftRestaurantTableViewCell.h"
#import "RightRestaurantTableViewCell.h"
#import "GoodsListView.h"
#import "ShoppingCartView.h"
#import "ViewModel.h"
#import "RestaurantViewModel.h"

@interface RestaurantViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSInteger _selectIndex;
    BOOL _isScrollDown;
    NSInteger P;
    NSInteger M;
    NSInteger money;//余额
    
}

@property (nonatomic,strong) ShoppingCartView *shoppcartview;

@end

@implementation RestaurantViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [self.navigationController setNavigationBarHidden:NO animated:NO];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    

    [self Layout];
    
  

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdatemainUI:) name:@"updateUI" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteDate) name:@"deleteDate" object:nil];

    [self.leftTableView registerNib:[UINib nibWithNibName:@"LeftRestaurantTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.rightTableView registerNib:[UINib nibWithNibName:@"RightRestaurantTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell1"];

    
    _selectIndex = 0;
    _isScrollDown = YES;
    self.totalOrders = 0;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    [self update];
    
    self.leftTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.rightTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];


    self.shoppcartview  = [[ShoppingCartView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, CGRectGetWidth(self.view.bounds), 50) inView:self.view];
    [self.view addSubview:self.shoppcartview];

    
    CGRect rect = [self.view convertRect:self.shoppcartview.shoppingCartBtn.frame fromView:self.shoppcartview];
    
    _endPointX = rect.origin.x + 25;
    _endPointY = rect.origin.y + 25;
    
}

-(void)update{


    NSDictionary *dic =@{@"token":[NSUD objectForKey:@"token"]};
    NSLog(@"%@",dic);

    [RestaurantViewModel requestWithUrlForRestaurant:self andParam:dic success:^(NSMutableArray *model) {
        

        
            [self.categoryData removeAllObjects];
            [self.foodData removeAllObjects];
            [self.ordersArray removeAllObjects];
    
        for (NSDictionary *dic in model) {
//            [self.SignLbale setTitle:dic[@"name"] forState:UIControlStateNormal];
            for (NSDictionary *dic1 in dic[@"dishesTypeDP"]) {
        CategoryModel *model = [[CategoryModel alloc] initWithDictionary:dic1 error:nil];

                NSLog(@"%@",  model);
                
            [self.categoryData addObject:model];
            NSMutableArray *datas = [[NSMutableArray alloc]init];
                for (NSDictionary *dic2 in model.dishesDP) {
            FoodModel *fmodel  =[FoodModel mj_objectWithKeyValues:dic2];
                        [datas addObject:fmodel];

                }
                [self.foodData addObject:datas];
                
            }
        }
        
            [self.rightTableView reloadData];
            [self.leftTableView reloadData];
        
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                                        animated:YES
                                  scrollPosition:UITableViewScrollPositionNone];
        
        
    } failure:^(NSString *error) {
        [MBProgressHUD showError:error toView:self.view];

    }];
    
    
    
}


#pragma mark - TableView DataSource Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_leftTableView == tableView){
        return 1;
    }else{
        return self.categoryData.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_leftTableView == tableView){
        return self.categoryData.count;
    }else{
        return [self.foodData[section] count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (_leftTableView == tableView){
        LeftRestaurantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        FoodModel *model = self.categoryData[indexPath.row];
        cell.name.text = model.name;
        return cell;
    }else{

        RightRestaurantTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell1"];
        
            FoodModel *model = self.foodData[indexPath.section][indexPath.row];
        
            cell.model = model;
        
        
        __weak __typeof(&*cell)weakCell =cell;
        __block __typeof(self)bself = self;
        cell.plusBlock = ^(NSInteger nCount,BOOL animated,NSString *fid){
            
            
            model.amount = [NSString stringWithFormat:@"%ld",nCount];
            [self.foodData addObject:model];

            CGRect parentRect = [weakCell convertRect:weakCell.plusBUtton.frame toView:self.view];
           
            /**
             *   给当前选中商品添加一个数量
             */
            NSMutableDictionary * dic = [model mj_keyValues];

            
            [dic setObject:[NSNumber numberWithInteger:nCount] forKey:@"orderCount"];

            
            if (animated==YES) {
                
                
                bself.ordersArray = [ViewModel storeOrders:dic OrderData:self.ordersArray isAdded:YES];

                self.totalOrders ++;

                [self JoinCartAnimationWithRect:parentRect];
            }else{
                
                bself.ordersArray = [ViewModel storeOrders:dic OrderData:self.ordersArray isAdded:NO];

                self.totalOrders --;
            }
            
            bself.shoppcartview.OrderList.objects = self.ordersArray;
            [bself.shoppcartview updateFrame:self.shoppcartview.OrderList];
            [bself.shoppcartview.OrderList.tableView reloadData];
            bself.shoppcartview.badgeValue =  [ViewModel CountOthersWithorderData:self.ordersArray];
            double price = [ViewModel GetTotalPrice:bself.ordersArray];
            [bself.shoppcartview setTotalMoney:price];
            
        };
        
        return cell;
        
    }
}




- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView)
    {
        return 30;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath {
    
    if (_rightTableView == tableView)
    {
        return 100;
    }else{
        return 50;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView)
    {
        TableViewHeaderView *view = [[TableViewHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
        FoodModel *model = self.categoryData[section];
        view.name.text = model.name;
        return view;
    }
    return nil;
}

// TableView分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向上，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView)
        && !_isScrollDown
        && (_rightTableView.dragging || _rightTableView.decelerating))
    {
        [self selectRowAtIndexPath:section];
    }
}

// TableView分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向下，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView)
        && _isScrollDown
        && (_rightTableView.dragging || _rightTableView.decelerating))
    {
        [self selectRowAtIndexPath:section + 1];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        _selectIndex = indexPath.row;
//        [self scrollToTopOfSection:_selectIndex animated:YES];
        [_leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_selectIndex inSection:0]
                              atScrollPosition:UITableViewScrollPositionTop
                                      animated:YES];
        
        
        // 计算出 右侧 tableView 将要 滚动的 位置
        NSIndexPath *moveToIndexPath = [NSIndexPath indexPathForRow:0 inSection:indexPath.row];
        
        // 将 rightTableView 移动到对应的 位置
        [self.rightTableView scrollToRowAtIndexPath:moveToIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        

        
    }
}

//- (void)scrollToTopOfSection:(NSInteger)section animated:(BOOL)animated
//{
//    CGRect headerRect = [self.rightTableView rectForSection:section];
//    CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y - _rightTableView.contentInset.top);
//    [self.rightTableView setContentOffset:topOfHeader animated:animated];
//}

// 当拖动右边TableView的时候，处理左边TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]
                                animated:YES
                          scrollPosition:UITableViewScrollPositionTop];
}

#pragma mark - UISrcollViewDelegate
// 标记一下RightTableView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat lastOffsetY = 0;
    
    UITableView *tableView = (UITableView *) scrollView;
    if (_rightTableView == tableView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




- (IBAction)pop:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];

}




#pragma mark -加入购物车动画
-(void) JoinCartAnimationWithRect:(CGRect)rect
{
    
    CGFloat startX = rect.origin.x;
    CGFloat startY = rect.origin.y;
    
    _path= [UIBezierPath bezierPath];
    [_path moveToPoint:CGPointMake(startX, startY)];
    //三点曲线
    [_path addCurveToPoint:CGPointMake(_endPointX, _endPointY)
             controlPoint1:CGPointMake(startX, startY)
             controlPoint2:CGPointMake(startX - 180, startY - 200)];
    
    _dotLayer = [CALayer layer];
    _dotLayer.backgroundColor = [UIColor redColor].CGColor;
    _dotLayer.frame = CGRectMake(0, 0, 15, 15);
    _dotLayer.cornerRadius = (15 + 15) /4;
    [self.view.layer addSublayer:_dotLayer];
    [self groupAnimation];
    
}

#pragma mark - 组合动画
-(void)groupAnimation
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    
    CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"alpha"];
    alphaAnimation.duration = 0.5f;
    alphaAnimation.fromValue = [NSNumber numberWithFloat:1.0];
    alphaAnimation.toValue = [NSNumber numberWithFloat:0.1];
    alphaAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,alphaAnimation];
    groups.duration = 0.8f;
    groups.removedOnCompletion = NO;
    groups.fillMode = kCAFillModeForwards;
    groups.delegate = self;
    [groups setValue:@"groupsAnimation" forKey:@"animationName"];
    [_dotLayer addAnimation:groups forKey:nil];
    
    
    [self performSelector:@selector(removeFromLayer:) withObject:_dotLayer afterDelay:0.8f];
    
}

- (void)removeFromLayer:(CALayer *)layerAnimation{
    
    
    
    //创建动画
    CAKeyframeAnimation * keyAnimaion = [CAKeyframeAnimation animation];
    keyAnimaion.keyPath = @"transform.rotation";
    keyAnimaion.values = @[@(-10 / 180.0 * M_PI),@(10 /180.0 * M_PI),@(-10/ 180.0 * M_PI),@(0)];//度数转弧度
    
    keyAnimaion.removedOnCompletion = NO;
    keyAnimaion.fillMode = kCAFillModeForwards;
    keyAnimaion.duration = 0.3;
    keyAnimaion.repeatCount = 1;
    [self.shoppcartview.shoppingCartBtn.layer addAnimation:keyAnimaion forKey:nil];
    

    [layerAnimation removeFromSuperlayer];
}



#pragma mark - 通知更新
-(void)UpdatemainUI:(NSNotification *)Notification{
    
    NSMutableDictionary *dic =[NSMutableDictionary dictionaryWithDictionary: Notification.userInfo];
    //重新计算订单数组。
    self.ordersArray = [ViewModel storeOrders:dic[@"update"] OrderData:self.ordersArray isAdded:[dic[@"isAdd"] boolValue]];
    self.shoppcartview.OrderList.objects = self.ordersArray;
    //设置高度。
    [self.shoppcartview updateFrame:self.shoppcartview.OrderList];
    [self.shoppcartview.OrderList.tableView reloadData];
    //设置数量、价格
    self.shoppcartview.badgeValue =  [ViewModel CountOthersWithorderData:self.ordersArray];
    double price = [ViewModel GetTotalPrice:self.ordersArray];
    [self.shoppcartview setTotalMoney:price];
    
    
    //重新设置数据源
    self.foodData = [ViewModel UpdateArray:self.foodData atSelectDictionary:dic[@"update"]] ;

    [self.rightTableView reloadData];
    
}

//-(void)dealloc{
//    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"updateUI"];
//    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"deleteDate"];
//
//}



-(void)Layout
{
    
    if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"568.0")) {
        
        self.LeftTableW.constant = 60;
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"667.0")){
        
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"736.0")){
        
        
    }else if (SYSTEM_VERSION_EQUAL_TO_W_orH(SCREEN_HEIGHT, @"812.0")){
        
        self.foodB.constant = 16;
        self.foodB1.constant = 16;
        
    }
    
    
    
}




-(void)deleteDate{
    
    [self update];
    
}

- (NSMutableArray *)categoryData
{
    if (!_categoryData)
    {
        _categoryData = [[NSMutableArray alloc]init];
    }
    return _categoryData;
}

- (NSMutableArray *)foodData
{
    if (!_foodData)
    {
        _foodData = [[NSMutableArray alloc]init];
    }
    return _foodData;
}

- (NSMutableArray *)ordersArray
{
    if (!_ordersArray)
    {
        _ordersArray = [[NSMutableArray alloc]init];
    }
    return _ordersArray;
}


@end
